package com.jochen.core.assets;

import com.badlogic.gdx.Gdx
import com.badlogic.gdx.assets.AssetManager
import com.badlogic.gdx.assets.loaders.FileHandleResolver
import com.badlogic.gdx.graphics.g2d.BitmapFont
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGenerator
import com.badlogic.gdx.graphics.g2d.freetype.FreeTypeFontGeneratorLoader
import com.badlogic.gdx.graphics.g2d.freetype.FreetypeFontLoader
import com.badlogic.gdx.maps.tiled.TiledMap
import com.badlogic.gdx.maps.tiled.TmxMapLoader
import com.badlogic.gdx.utils.Disposable

class AssetService(
    private val fileHandleResolver: FileHandleResolver
    ): Disposable{
    
    private val assetManager: AssetManager = AssetManager(fileHandleResolver).apply{
        setLoader(TiledMap::class.java,TmxMapLoader(fileHandleResolver))
        setLoader(FreeTypeFontGenerator::class.java,FreeTypeFontGeneratorLoader(fileHandleResolver))
        setLoader(BitmapFont::class.java, ".ttf", FreetypeFontLoader(fileHandleResolver))
    }
    
    fun <T> load(asset: Asset<T>): T{
        assetManager.load(asset.descriptor)
        assetManager.finishLoading()
        return assetManager.get(asset.descriptor)
    }
    
    fun <T> unload(asset: Asset<T>){
        assetManager.unload(asset.descriptor.fileName)
    }
    
    fun <T> queue(asset: Asset<T>){
        assetManager.load(asset.descriptor)
    }
    
    fun <T> get(asset: Asset<T>): T = assetManager.get(asset.descriptor)
    
    fun update(): Boolean = assetManager.update()
    
    val progress: Float get() = assetManager.progress
    
    override fun dispose(){
        assetManager.dispose()
    }
}